/*
	Copyright (C) 2008 by Jean-François Geyelin
	jfgeyelin@gmail.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the
	Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "all.h"

std::string relativePath = "data/";

std::string getFullPath(std::string s) {

    return relativePath+s;
}


std::string getFullPath(const char *fileName) {
    std::string s(fileName);
    return getFullPath(s);
}

std::string getFullPathWithString(std::string fileName) {
    return getFullPath(fileName);
}

FILE *fopen_safe(const char *fileName, const char *mode) {
	FILE *f = fopen(getFullPath(fileName).c_str(),mode);
	if (f==NULL) {
        LOG_ERROR("failed to open file\n");
        LOG_ERROR("\tpath was:%s\n",getFullPath(fileName).c_str());
        LOG_ERROR("\tfor:%s\n",fileName);
    }
	return f;
}

void remove_safe(const char *fileName) {
    if (remove(getFullPath(fileName).c_str())!=0) {
        LOG_ERROR("failed to delete file\n");
        LOG_ERROR("\tpath was:%s\n",getFullPath(fileName).c_str());
        LOG_ERROR("\tfor:%s\n",fileName);
    }
}

#ifdef FMOD_3

FSOUND_SAMPLE *FSOUND_Sample_Load_safe(int index, const char *name_or_data, unsigned int inputmode, int offset, int length) {
    FSOUND_SAMPLE *sound = FSOUND_Sample_Load(index, getFullPath(name_or_data).c_str(), inputmode, offset, length);
    if (sound==NULL) {
        LOG_ERROR("failed to load sound\n");
        LOG_ERROR("\tpath was:%s\n",getFullPath(name_or_data).c_str());
    }
    return sound;
}

#endif

SDL_Surface *SDL_LoadBMP_safe(const char *fileName) {
    SDL_Surface * s = SDL_LoadBMP(getFullPath(fileName).c_str());
    if (s==NULL) {
        LOG_ERROR("failed to load image (SDL_LoadBMP_safe)\n");
        LOG_ERROR("\tpath was:%s\n",getFullPath(fileName).c_str());
    }
    return s;
}

SDL_Surface *IMG_Load_safe(const char *fileName) {
    SDL_Surface * s = IMG_Load(getFullPath(fileName).c_str());
    if (s==NULL) {
        LOG_ERROR("failed to load image (IMG_Load_safe)\n");
        LOG_ERROR("\tpath was:%s\n",getFullPath(fileName).c_str());
    }
    return s;
}


void SDL_SaveBMP_safe(SDL_Surface *s, const char *path) {
    if(s!=NULL) {
        SDL_SaveBMP(s,getFullPath(path).c_str());
    }
    else {
        LOG_ERROR("failed to save image (SDL_SaveBMP_safe)\n");
    }
}
